<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备id" prop="deviceId">
        <el-input
          v-model="queryParams.deviceId"
          placeholder="请输入设备id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['real:detect:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['real:detect:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['real:detect:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['real:detect:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="handleRefresh"
          :loading="loading"
        >刷新</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="displayDetectList"
      @selection-change="handleSelectionChange"
      :row-class-name="getRowClassName"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="时间戳" align="center" prop="timestamp" width="180">
        <template slot-scope="scope">
          <span>{{ formatTimestamp(scope.row.timestamp) }}</span>
          <el-tag v-if="isRecentUpdate(scope.row)" type="success" size="mini" style="margin-left: 5px;">
            实时
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="设备id" align="center" prop="deviceId" />
      <el-table-column label="温度" align="center" prop="temperature">
        <template slot-scope="scope">
          <span :class="{ 'realtime-data': isRecentUpdate(scope.row) }">
            {{ scope.row.temperature }}°C
          </span>
        </template>
      </el-table-column>
      <el-table-column label="x轴均方根" align="center" prop="xRms">
        <template slot-scope="scope">
          <span :class="{ 'realtime-data': isRecentUpdate(scope.row) }">
            {{ scope.row.xRms }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="y轴均方根" align="center" prop="yRms">
        <template slot-scope="scope">
          <span :class="{ 'realtime-data': isRecentUpdate(scope.row) }">
            {{ scope.row.yRms }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="z轴均方根" align="center" prop="zRms">
        <template slot-scope="scope">
          <span :class="{ 'realtime-data': isRecentUpdate(scope.row) }">
            {{ scope.row.zRms }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="x轴峰值" align="center" prop="xPeak">
        <template slot-scope="scope">
          <span :class="{ 'realtime-data': isRecentUpdate(scope.row) }">
            {{ scope.row.xPeak }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="y轴峰值" align="center" prop="yPeak">
        <template slot-scope="scope">
          <span :class="{ 'realtime-data': isRecentUpdate(scope.row) }">
            {{ scope.row.yPeak }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="z轴峰值" align="center" prop="zPeak">
        <template slot-scope="scope">
          <span :class="{ 'realtime-data': isRecentUpdate(scope.row) }">
            {{ scope.row.zPeak }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag
            :type="getStatusType(scope.row.status)"
            :class="{ 'realtime-data': isRecentUpdate(scope.row) }"
          >
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['real:detect:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['real:detect:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备检测对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备id" prop="deviceId">
          <el-input v-model="form.deviceId" placeholder="请输入设备id" />
        </el-form-item>
        <el-form-item label="温度" prop="temperature">
          <el-input v-model="form.temperature" placeholder="请输入温度" />
        </el-form-item>
        <el-form-item label="x轴均方根" prop="xRms">
          <el-input v-model="form.xRms" placeholder="请输入x轴均方根" />
        </el-form-item>
        <el-form-item label="y轴均方根" prop="yRms">
          <el-input v-model="form.yRms" placeholder="请输入y轴均方根" />
        </el-form-item>
        <el-form-item label="z轴均方根" prop="zRms">
          <el-input v-model="form.zRms" placeholder="请输入z轴均方根" />
        </el-form-item>
        <el-form-item label="x轴峰值" prop="xPeak">
          <el-input v-model="form.xPeak" placeholder="请输入x轴峰值" />
        </el-form-item>
        <el-form-item label="y轴峰值" prop="yPeak">
          <el-input v-model="form.yPeak" placeholder="请输入y轴峰值" />
        </el-form-item>
        <el-form-item label="z轴峰值" prop="zPeak">
          <el-input v-model="form.zPeak" placeholder="请输入z轴峰值" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDetect, getDetect, delDetect, addDetect, updateDetect } from "@/api/real/detect";
import { mapGetters, mapActions } from 'vuex'
import WebSocketStatus from '@/components/WebSocketStatus'

export default {
  name: "Detect",
  components: {
    WebSocketStatus
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备检测表格数据
      detectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceId: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deviceId: [
          { required: true, message: "设备id不能为空", trigger: "blur" }
        ],
        temperature: [
          { required: true, message: "温度不能为空", trigger: "blur" }
        ],
        xRms: [
          { required: true, message: "x轴均方根不能为空", trigger: "blur" }
        ],
        yRms: [
          { required: true, message: "y轴均方根不能为空", trigger: "blur" }
        ],
        zRms: [
          { required: true, message: "z轴均方根不能为空", trigger: "blur" }
        ],
        xPeak: [
          { required: true, message: "x轴峰值不能为空", trigger: "blur" }
        ],
        yPeak: [
          { required: true, message: "y轴峰值不能为空", trigger: "blur" }
        ],
        zPeak: [
          { required: true, message: "z轴峰值不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ]
      },
      // WebSocket相关
      enableWebSocket: true,
      realtimeUpdates: new Map(), // 存储实时更新的数据
      // 轮询相关
      pollingTimer: null,
      pollingInterval: 2000,
      lastPollingUpdate: null
    };
  },
  computed: {
    ...mapGetters('websocket', ['connectionInfo']),

    // 显示的检测列表（合并实时数据和历史数据）
    displayDetectList() {
      if (!this.enableWebSocket) {
        return this.detectList
      }

      // 合并WebSocket实时数据和历史数据
      const realtimeData = this.$store.state.websocket.deviceInfo
      const mergedList = [...this.detectList]

      // 更新或添加实时数据
      realtimeData.forEach(realtimeItem => {
        const index = mergedList.findIndex(item => item.deviceId === realtimeItem.deviceId)
        if (index !== -1) {
          // 更新现有数据
          mergedList[index] = {
            ...mergedList[index],
            ...realtimeItem,
            isRealtime: true,
            realtimeTimestamp: Date.now()
          }
        } else {
          // 添加新的实时数据
          mergedList.unshift({
            ...realtimeItem,
            isRealtime: true,
            realtimeTimestamp: Date.now()
          })
        }
      })

      return mergedList
    }
  },
  created() {
    this.getList();
    this.initDataSource();
  },
  beforeDestroy() {
    this.cleanup();
  },
  methods: {
    ...mapActions('websocket', ['initWebSocket', 'disconnectWebSocket']),

    /** 查询设备检测列表 */
    getList() {
      this.loading = true;
      listDetect(this.queryParams).then(response => {
        this.detectList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 初始化数据源 */
    initDataSource() {
      if (this.enableWebSocket) {
        this.initWebSocketConnection();
      } else {
        this.startPolling();
      }
    },

    /** 初始化WebSocket连接 */
    async initWebSocketConnection() {
      try {
        await this.initWebSocket();
        this.$message.success('WebSocket连接已建立');
      } catch (error) {
        console.error('WebSocket初始化失败:', error);
        this.$message.error('WebSocket连接失败，已切换到轮询模式');
        this.enableWebSocket = false;
        this.startPolling();
      }
    },

    /** 开始轮询 */
    startPolling() {
      this.stopPolling();
      this.pollingTimer = setInterval(() => {
        this.getList();
        this.lastPollingUpdate = new Date().toLocaleTimeString();
      }, this.pollingInterval);
    },

    /** 停止轮询 */
    stopPolling() {
      if (this.pollingTimer) {
        clearInterval(this.pollingTimer);
        this.pollingTimer = null;
      }
    },

    /** 处理WebSocket开关切换 */
    handleWebSocketToggle(enabled) {
      if (enabled) {
        this.stopPolling();
        this.initWebSocketConnection();
      } else {
        this.disconnectWebSocket();
        this.startPolling();
      }
    },

    /** 刷新数据 */
    handleRefresh() {
      if (this.enableWebSocket) {
        // WebSocket模式下重新获取历史数据
        this.getList();
      } else {
        // 轮询模式下立即更新
        this.getList();
        this.lastPollingUpdate = new Date().toLocaleTimeString();
      }
    },

    /** 清理资源 */
    cleanup() {
      this.stopPolling();
      this.disconnectWebSocket();
    },

    /** 格式化时间戳 */
    formatTimestamp(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      return date.toLocaleString();
    },

    /** 判断是否为最近更新的数据 */
    isRecentUpdate(row) {
      if (!row.realtimeTimestamp) return false;
      const now = Date.now();
      return (now - row.realtimeTimestamp) < 5000; // 5秒内的更新显示为实时
    },

    /** 获取状态类型 */
    getStatusType(status) {
      switch (status) {
        case '正常':
        case 'online':
          return 'success';
        case '异常':
        case 'error':
          return 'danger';
        case '警告':
        case 'warning':
          return 'warning';
        default:
          return 'info';
      }
    },

    /** 获取行样式类名 */
    getRowClassName({ row }) {
      if (this.isRecentUpdate(row)) {
        return 'realtime-row';
      }
      return '';
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        timestamp: null,
        deviceId: null,
        temperature: null,
        xRms: null,
        yRms: null,
        zRms: null,
        xPeak: null,
        yPeak: null,
        zPeak: null,
        status: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.timestamp)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备检测";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const timestamp = row.timestamp || this.ids
      getDetect(timestamp).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改设备检测";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.timestamp != null) {
            updateDetect(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDetect(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const timestamps = row.timestamp || this.ids;
      this.$modal.confirm('是否确认删除设备检测编号为"' + timestamps + '"的数据项？').then(function() {
        return delDetect(timestamps);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('real/detect/export', {
        ...this.queryParams
      }, `detect_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style lang="scss" scoped>
.websocket-status-card {
  margin-bottom: 16px;

  .clearfix::after {
    content: "";
    display: table;
    clear: both;
  }
}

.polling-status {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #909399;
  font-size: 14px;

  .el-icon-refresh {
    animation: rotate 2s linear infinite;
  }

  .last-update {
    margin-left: auto;
    font-size: 12px;
    color: #c0c4cc;
  }
}

.realtime-data {
  color: #67c23a;
  font-weight: 500;
  animation: pulse 1s ease-in-out;
}

@keyframes pulse {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0.7;
  }
  100% {
    opacity: 1;
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>

<style lang="scss">
.realtime-row {
  background-color: #f0f9ff !important;
  animation: highlight 2s ease-in-out;
}

@keyframes highlight {
  0% {
    background-color: #e1f3d8 !important;
  }
  100% {
    background-color: #f0f9ff !important;
  }
}
</style>
